<template>
  <view class="environment-data">
    <view class="section-title">
      <text class="title-text">环境数据</text>
      <text class="update-time">更新时间：{{ lastUpdateTime }}</text>
    </view>
    
    <!-- 添加天气状况显示 -->
    <view class="weather-info" v-if="weatherInfo">
      <text class="weather-text">{{ weatherInfo.weather }}</text>
      <text class="wind-info">{{ weatherInfo.windInfo }}</text>
    </view>
    
    <view class="data-grid">
      <!-- 温度 -->
      <view class="data-card">
        <view class="data-icon">
          <image src="/static/index/wdj.png" mode="aspectFit" class="icon-image"></image>
        </view>
        <view class="data-info">
          <text class="data-value">{{ temperature }}°C</text>
          <text class="data-label">温度</text>
        </view>
      </view>
      
      <!-- 湿度 -->
      <view class="data-card">
        <view class="data-icon">
          <image src="/static/index/wet.png" mode="aspectFit" class="icon-image"></image>
        </view>
        <view class="data-info">
          <text class="data-value">{{ humidity }}%</text>
          <text class="data-label">湿度</text>
        </view>
      </view>
      
      <!-- 光照 -->
      <view class="data-card">
        <view class="data-icon">
          <image src="/static/index/sun.png" mode="aspectFit" class="icon-image"></image>
        </view>
        <view class="data-info">
          <text class="data-value">{{ light }}lux</text>
          <text class="data-label">光照</text>
        </view>
      </view>
      
      <!-- 土壤湿度 -->
      <view class="data-card">
        <view class="data-icon">
          <image src="/static/index/leaf.png" mode="aspectFit" class="icon-image"></image>
        </view>
        <view class="data-info">
          <text class="data-value">{{ soilMoisture }}%</text>
          <text class="data-label">土壤湿度</text>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="iconfont icon-loading"></text>
      <text>正在获取数据...</text>
    </view>
    
    <!-- 错误状态 -->
    <view class="error-state" v-if="error">
      <text class="iconfont icon-error"></text>
      <text>{{ error }}</text>
      <view class="retry-btn" @tap="fetchEnvironmentData">重试</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';

// 定义props
const props = defineProps<{
  cityCode?: string; // 城市编码
}>();

// 环境数据状态
const temperature = ref('--');
const humidity = ref('--');
const light = ref('--');
const soilMoisture = ref('--');
const lastUpdateTime = ref('--');
const loading = ref(false);
const error = ref('');
const weatherInfo = ref<{
  weather: string;
  windInfo: string;
} | null>(null);

// API配置
const API_KEY = 'afd27fc88fbccf482c099bf12a78139b';
const API_URL = 'https://restapi.amap.com/v3/weather/weatherInfo'; // 高德天气API

// 获取环境数据
const fetchEnvironmentData = async () => {
  if (!props.cityCode) {
    console.error('未提供城市编码');
    error.value = '未设置城市信息';
    return;
  }

  loading.value = true;
  error.value = '';
  
  try {
    console.log('开始获取天气数据，城市编码:', props.cityCode);
    const response = await uni.request({
      url: API_URL,
      method: 'GET',
      data: {
        key: API_KEY,
        city: props.cityCode,
        extensions: 'base',
        output: 'JSON'
      }
    });
    
    console.log('高德天气API响应:', response);
    
    if (response.statusCode === 200 && response.data.status === '1') {
      const weatherData = response.data.lives?.[0];
      
      if (!weatherData || !Array.isArray(response.data.lives) || response.data.lives.length === 0) {
        console.error('天气数据格式错误:', response.data);
        throw new Error('天气数据格式错误');
      }
      
      console.log('解析后的天气数据:', weatherData);
      
      // 更新数据
      temperature.value = weatherData.temperature || '--';
      humidity.value = weatherData.humidity || '--';
      
      // 更新天气信息
      weatherInfo.value = {
        weather: weatherData.weather || '未知',
        windInfo: `${weatherData.winddirection || '未知'}风 ${weatherData.windpower || '0'}级`
      };
      
      // 获取风向和风力信息
      const windInfo = (weatherData.winddirection || '未知') + '风 ' + (weatherData.windpower || '0') + '级';
      
      // 由于高德API不提供光照和土壤湿度数据，这里使用模拟数据
      const hour = new Date().getHours();
      let lightValue;
      if (hour >= 6 && hour <= 18) {
        // 白天光照强度随太阳高度变化
        const maxLight = 80000; // 最大光照强度
        const minLight = 20000; // 最小光照强度
        const noonHour = 12; // 正午时间
        const hourDiff = Math.abs(hour - noonHour);
        const lightFactor = 1 - (hourDiff / 6); // 6小时为半天
        lightValue = Math.floor(minLight + (maxLight - minLight) * lightFactor);
      } else {
        // 夜间光照强度
        lightValue = Math.floor(Math.random() * 1000); // 0-1000 lux
      }
      
      // 根据天气状况调整光照强度
      const weatherCondition = weatherData.weather || '';
      if (weatherCondition.includes('雨') || weatherCondition.includes('雪')) {
        lightValue = Math.floor(lightValue * 0.3); // 雨雪天气光照降低
      } else if (weatherCondition.includes('阴') || weatherCondition.includes('云')) {
        lightValue = Math.floor(lightValue * 0.6); // 阴天光照降低
      }
      
      light.value = lightValue.toString();
      
      // 根据温度和湿度模拟土壤湿度
      const temp = parseFloat(weatherData.temperature) || 25;
      const hum = parseFloat(weatherData.humidity) || 60;
      let soilMoistureValue;
      
      if (weatherCondition.includes('雨')) {
        soilMoistureValue = Math.floor(Math.random() * 20 + 60); // 雨天土壤湿度 60-80%
      } else if (weatherCondition.includes('雪')) {
        soilMoistureValue = Math.floor(Math.random() * 10 + 50); // 雪天土壤湿度 50-60%
      } else {
        // 根据温度和湿度计算土壤湿度
        const baseMoisture = 40 + (hum - 50) * 0.5; // 基础湿度
        const tempFactor = (temp - 20) * 0.5; // 温度影响因子
        soilMoistureValue = Math.floor(baseMoisture - tempFactor);
        // 确保土壤湿度在合理范围内
        soilMoistureValue = Math.max(30, Math.min(80, soilMoistureValue));
      }
      
      soilMoisture.value = soilMoistureValue.toString();
      lastUpdateTime.value = new Date().toLocaleTimeString();
      
      // 更新天气状况
      console.log('当前天气状况:', {
        temperature: temperature.value,
        humidity: humidity.value,
        light: light.value,
        soilMoisture: soilMoisture.value,
        weather: weatherData.weather,
        windInfo: windInfo
      });
      
    } else {
      console.error('API返回错误:', response.data);
      throw new Error('获取天气数据失败: ' + (response.data.info || '未知错误'));
    }
  } catch (e) {
    console.error('获取环境数据失败:', e);
    error.value = '获取数据失败，请稍后重试';
    
    // 重置天气信息
    weatherInfo.value = null;
    
    // 如果API调用失败，使用模拟数据
    const now = new Date();
    const hour = now.getHours();
    
    // 根据时间生成合理的模拟数据
    temperature.value = (20 + Math.random() * 10).toFixed(1);
    humidity.value = (50 + Math.random() * 20).toFixed(0);
    
    // 根据时间生成光照数据
    if (hour >= 6 && hour <= 18) {
      const maxLight = 80000;
      const minLight = 20000;
      const noonHour = 12;
      const hourDiff = Math.abs(hour - noonHour);
      const lightFactor = 1 - (hourDiff / 6);
      light.value = Math.floor(minLight + (maxLight - minLight) * lightFactor).toString();
    } else {
      light.value = Math.floor(Math.random() * 1000).toString();
    }
    
    // 生成合理的土壤湿度数据
    soilMoisture.value = (40 + Math.random() * 20).toFixed(0);
    lastUpdateTime.value = now.toLocaleTimeString() + ' (模拟数据)';
  } finally {
    loading.value = false;
  }
};

// 监听城市编码变化
watch(() => props.cityCode, (newCityCode) => {
  if (newCityCode) {
    fetchEnvironmentData();
  }
});

// 组件挂载时获取数据
onMounted(() => {
  if (props.cityCode) {
    fetchEnvironmentData();
  }
});
</script>

<style lang="scss">
.environment-data {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20rpx;
  margin: 20rpx;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .title-text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .update-time {
      font-size: 24rpx;
      color: #999999;
    }
  }
  
  .data-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    
    .data-card {
      background-color: #f8f9fa;
      border-radius: 8px;
      padding: 20rpx;
      display: flex;
      align-items: center;
      
      .data-icon {
        width: 80rpx;
        height: 80rpx;
        background-color: rgba(76, 175, 80, 0.1);
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
        
        .icon-image {
          width: 40rpx;
          height: 40rpx;
        }
      }
      
      .data-info {
        flex: 1;
        
        .data-value {
          font-size: 36rpx;
          font-weight: bold;
          color: #333333;
          display: block;
          margin-bottom: 4rpx;
        }
        
        .data-label {
          font-size: 24rpx;
          color: #666666;
        }
      }
    }
  }
  
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx 0;
    
    .iconfont {
      font-size: 48rpx;
      color: #4CAF50;
      margin-bottom: 20rpx;
      animation: rotate 1s linear infinite;
    }
    
    text {
      font-size: 28rpx;
      color: #666666;
    }
  }
  
  .error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx 0;
    
    .iconfont {
      font-size: 48rpx;
      color: #f44336;
      margin-bottom: 20rpx;
    }
    
    text {
      font-size: 28rpx;
      color: #666666;
      margin-bottom: 20rpx;
    }
    
    .retry-btn {
      padding: 12rpx 40rpx;
      background-color: #4CAF50;
      color: #ffffff;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
  }

  .weather-info {
    margin: 10rpx 0 20rpx;
    padding: 10rpx 20rpx;
    background-color: rgba(76, 175, 80, 0.1);
    border-radius: 8rpx;
    
    .weather-text {
      font-size: 28rpx;
      color: #333333;
      margin-right: 20rpx;
    }
    
    .wind-info {
      font-size: 24rpx;
      color: #666666;
    }
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 